package com.rock.code.province.hn.coll;

import com.rock.code.common.util.Img2Str;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.params.CoreConnectionPNames;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.zip.GZIPInputStream;

/**
 * url 探测
 *
 * @author zhangli
 * @version V1.0
 * @create 2019-04-23 17:31
 **/
public class DetectCase {

    private HashMap<String, String> mapPARAMS = new HashMap<>();

    HttpClient client = null;

    String picFile = "/home/common/tmp/CreateImage.jpg";

    public void initHttpClient() {
        /* 根据各种情况进行调用 */
        if (client == null) {
            client = new HttpClient();
            // 加入url重试
            DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(6, false);
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);

            // 设置时间超时
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120000);
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120000);

            client.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
            client.getHttpConnectionManager().getParams().setSoTimeout(120000);
            // 设置每个主机的最大连接数
            client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(32);// very
            // important!!
            client.getHttpConnectionManager().getParams().setMaxTotalConnections(256);// very
        }

    }

    public String jet(String url, String METHOD, String postData,boolean authPic,String... cookies) {

        String responseContent = "";
        HttpMethod post = null;
        String urlContent_type = "1";//手动修改
        String method = METHOD;//手动修改 "POST"、"GET"、"PIC"

        String url1 = url;//手动修改
        if (method.toUpperCase().equals("GET") || method.toUpperCase().equals("PIC")) {

            post = new GetMethod(url1);

        } else {
            post = new PostMethod(url1);


//            String xmlcontent = "user_name=%79%70%78%67&password=%1%6%14%6%7%5%91%83%89%127&language=1&password1=&otp_value=&check=6c54d5c75bc90d20bd75105d75766727&verify=&code=";

            if(authPic){
//                String read = JOptionPane.showInputDialog("验证码：");
                String read = "";
                Img2Str img2Str = new Img2Str();
                try {
                    read = img2Str.getCode(picFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                postData += read;
            }
//            ((PostMethod) post).setRequestBody(xmlcontent);
            ((PostMethod) post).setRequestBody(convertToNameParas(postData));
//            ((PostMethod) post).setRequestBody();
//            post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            if ("1".equalsIgnoreCase(urlContent_type)) {
                post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            } else if ("2".equalsIgnoreCase(urlContent_type)) {
                post.addRequestHeader("Content-Type", "application/json");
            } else {
                post.addRequestHeader("Content-Type", "multipart/form-data");
            }
        }
        post.addRequestHeader("Accept-Language", "zh-CN,zh;q=0.9");
//        post.addRequestHeader("Cache-Control", "no-cache");
        post.addRequestHeader("Connection", "Keep-Alive");
        post.addRequestHeader("Referer", "http://10.230.39.121/html/login.html");
        post.addRequestHeader("X-Requested-With", "XMLHttpRequest");

        post.addRequestHeader("Accept", "*/*");
        post.addRequestHeader("Accept-Encoding", "gzip,deflate");
        post.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36");
//        post.addRequestHeader("Accept-Charset", "iso-8859-1,*,utf-8");

//        addCookie(client, post);
        autoCookie(post,client);//自动处理cookie
        try {
            // 图形验证码获取，上传
            if (method.toUpperCase().equals("PIC")) {
//                executeMethod(client, post);
                client.executeMethod(post);
                InputStream inStream = null;
                BufferedImage iag = null;
                inStream = post.getResponseBodyAsStream();
                iag = ImageIO.read(inStream);
                BufferedImage newBufferedImage = new BufferedImage(iag.getWidth(), iag.getHeight(), BufferedImage.TYPE_INT_RGB);
                newBufferedImage.createGraphics().drawImage(iag, 0, 0, Color.WHITE, null);
                ImageIO.write(newBufferedImage, "jpg", new File(picFile));

//                JFrame jFrame = new JFrame();
//                JLabel jLabel = new JLabel(new ImageIcon("C:/tmp/CreateImage.png"));
//                jFrame.getContentPane().add(jLabel);
//                jFrame.setSize(100, 100);
//                jFrame.setTitle("验证码");
//                jFrame.setVisible(true);

                getHeaders(post, cookies);


            } else {
                responseContent = executeMethod(client, post);
                getHeaders(post, cookies);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

        return responseContent;
    }

    public String executeMethod(HttpClient client, HttpMethod post) {
        String content = "";
        try {

            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            client.getParams().setBooleanParameter("http.protocol.single-cookie-header", true);

            client.executeMethod(post);

            // 得到url访问返回的数据流
            // String content = "";

            content = getResponseBody(post);
//            System.out.println(post.getResponseBodyAsString());

//			content = post.getResponseBodyAsString()+getHeaders(post);

//            System.out.println("content:" + content);
            // 写到文件中
//			 writeContent(content);


            // 分析数据流，得到执行结果
//            Start.collKpi.busi_result = businessResult(content);

            // 取得后面的url访问所需的参数，并将其放入到session中
//            getSetSessionParams(content);

            // 取得后面的url访问所需的参数，并将其放入到HashMap中
            // getMapBusiParams(content);
//            web_reg_save_param(content);


        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;

    }

    String tmp = "";

    private void addCookie(HttpClient client, HttpMethod post) {
        String cookieStr = String.valueOf(mapPARAMS.get("COOKIE"));
        if (cookieStr != null && !cookieStr.trim().equalsIgnoreCase("null") && cookieStr.trim().length() > 0) {
            String [] cookieKey = cookieStr.split(";");


            if (tmp.length() < 1) {//第一次执行url tmp 是空
                Cookie[] cookies = client.getState().getCookies();
                StringBuffer buffer = new StringBuffer();

                for (String _cookieKey : cookieKey) {
                    String []kvs = _cookieKey.split("=");


                    for (int index = 0; index < cookies.length; index++) {
                        Cookie cookie = cookies[index];

                        if (kvs.length>1&&kvs[0].equalsIgnoreCase(cookie.toString().split("=")[0].trim())) {//如果cookie 中有相等的就不做处理
                            //如果是mapPARAMS 已经有这个cookie 了，就不进行处理说明之前已经处理过,直接弄过来就行
                            buffer.append(_cookieKey);
                            buffer.append("; ");
                        } else {//如果如果是mapPARAMS 没有这个cookie 就填加上
                            buffer.append(cookie.toString());
                            buffer.append("; ");
                        }
                    }
                }
                buffer.append(cookieStr);
                tmp = buffer.toString();
                if (buffer.toString().endsWith("; ")) {
                    tmp = buffer.substring(0, buffer.indexOf("; "));
                }

                client.getState().clearCookies();

            }else {
                Cookie[] cookies = client.getState().getCookies();
                StringBuffer buffer = new StringBuffer();

                for (String _cookieKey : cookieKey) {
                    String []kvs = _cookieKey.split("=");

                    for (int index = 0; index < cookies.length; index++) {
                        Cookie cookie = cookies[index];

                        if (kvs.length>1&&kvs[0].equalsIgnoreCase(cookie.toString().split("=")[0].trim())) {//如果cookie 中有相等的就不做处理
                            //如果是mapPARAMS 已经有这个cookie 了，就不进行处理说明之前已经处理过,直接弄过来就行
                            buffer.append(_cookieKey);
                            buffer.append("; ");
                        } else {//如果如果是mapPARAMS 没有这个cookie 就填加上
                            buffer.append(cookie.toString());
                            buffer.append("; ");
                        }
                    }
                }
                buffer.append(cookieStr);
                tmp = buffer.toString();
                if (buffer.toString().endsWith("; ")) {
                    tmp = buffer.substring(0, buffer.indexOf("; "));
                }

                client.getState().clearCookies();
            }
        } else {
            Cookie[] cookies = client.getState().getCookies();
            StringBuffer buffer = new StringBuffer();
            for (int index = 0; index < cookies.length; index++) {
                Cookie cookie = cookies[index];
                buffer.append(cookie.toString());
                buffer.append("; ");
            }
            tmp = buffer.toString();
            if (buffer.toString().endsWith("; ")) {
                tmp = buffer.substring(0, buffer.indexOf("; "));
            }
        }
        if (tmp.length() > 0) {
            client.getState().clearCookies();
            post.addRequestHeader("Cookie", tmp);
            System.out.println("============cookie="+tmp);
        }
    }

    /**
     * 根据post 的返回编码是gzip方式的话，进行对返回体解压缩，这样显示的内容不是乱码
     *
     * @param post
     * @return 获取解压缩后的返回体的内容
     */
    public String getResponseBody(HttpMethod post) {
        StringBuilder sbr = new StringBuilder();
        try {
            String charset = "utf-8";
            if (post.getResponseHeader("Content-Type") != null) {
                charset = post.getResponseHeader("Content-Type").getValue();
                if (charset.indexOf("charset") > 0) {
                    charset = charset.substring(charset.indexOf("charset") + 8);
                } else {
                    charset = "utf-8";
                }
            }
            BufferedReader br = null;

            String contentEncoding = "";
            if (post.getResponseHeader("Content-Encoding") != null) {
                contentEncoding = post.getResponseHeader("Content-Encoding")
                        .getValue();
                if (contentEncoding.indexOf("gzip") != -1) {
                    GZIPInputStream gzipin = new GZIPInputStream(
                            post.getResponseBodyAsStream());
                    br = new BufferedReader(new InputStreamReader(gzipin, charset));
                }
            } else {
                br = new BufferedReader(new InputStreamReader(
                        post.getResponseBodyAsStream(), charset));
            }

            String strTmp = null;
            while ((strTmp = br.readLine()) != null) {
                sbr.append(strTmp).append("\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sbr.toString();
    }

    public void saveJPEG(BufferedImage iag, String savePath) throws FileNotFoundException, IOException {
        OutputStream jos = new FileOutputStream(savePath);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(jos);
        JPEGEncodeParam jpegEP = JPEGCodec.getDefaultJPEGEncodeParam(iag);

        jpegEP.setQuality((float) 1, true);
        encoder.encode(iag, jpegEP);
        jos.flush();
        jos.close();
    }

    public void doCookie(String key,String machkey, String value) {
        String cookieStr = mapPARAMS.get("COOKIE");
        StringBuffer bu = new StringBuffer();
        if (cookieStr != null && !cookieStr.trim().equalsIgnoreCase("null") && cookieStr.trim().length() > 0) {
            String keyValues[] = cookieStr.split("; ");
            for (String keyValue : keyValues) {
                String keyAndValue[] = keyValue.split("=");
                if (machkey.equalsIgnoreCase(keyAndValue[0])) {
                    bu.append(key + "=" + value);
                    bu.append("; ");
                } else {
                    bu.append(keyValue);
                    bu.append("; ");

                }
            }
            String _tmp = bu.toString();
            if (bu.toString().endsWith("; ")) {
                _tmp = bu.substring(0, bu.indexOf("; "));
            }
            mapPARAMS.put("COOKIE", _tmp);
        }

    }

    /**
     * 获取返回头的内容
     *
     * @param post
     * @return String方式获取返回头的内容
     */
    public String getHeaders(HttpMethod post, String... cookie) {
        Header[] headers = post.getResponseHeaders();
        StringBuffer strHeaders = new StringBuffer();
        for (String getCookieKey : cookie) {
            String getKandV[] = getCookieKey.split("=");

            for (int index = 0; index < headers.length; index++) {
                Header header = headers[index];
                HeaderElement[] elements = header.getElements();
//                System.out.println("###############" + elements.toString() + header.getName() + ":" + header.getValue());
                if (header.getName().equalsIgnoreCase("Set-Cookie")) {
                    String[] _cks = header.getValue().split(";");
                    for (String _ck : _cks) {
                        if (_ck.length() > 1) {
                            if (_ck.split("=")[0].equalsIgnoreCase(getKandV[0])) {
//                                mapPARAMS.put("COOKIE",mapPARAMS.get("COOKIE"))
                                doCookie(getKandV[0],getKandV[1], _ck.split("=")[1]);

                            }
                        }

                    }

                }
                String headerValue = header.getValue();
                strHeaders.append(headerValue);
            }
        }

//        System.out.println("*************" + strHeaders);
        return "*************" + strHeaders;

    }

    public HashMap<String, String> getMapPARAMS() {
        return mapPARAMS;
    }

    public void setMapPARAMS(HashMap<String, String> mapPARAMS) {
        this.mapPARAMS = mapPARAMS;
    }

    /**
     * 将mapPARAMS中所有参数对转变为NameValuePair
     */
    public NameValuePair[] convertToNameParas() {

        int count = 0;
        int len = mapPARAMS.size();
        NameValuePair pair[] = new NameValuePair[len];
        for (Iterator i = mapPARAMS.keySet().iterator(); i.hasNext(); ) {
            Object key = i.next();
            Object value = mapPARAMS.get(key);
            pair[count] = new NameValuePair((String) key, (String) value);
            count++;

        }

        return pair;
    }

    /**
     * 将mapPARAMS中所有参数对转变为NameValuePair
     */
    public NameValuePair[] convertToNameParas(String xmlcontent) {

        int count = 0;
        String kvs[] = xmlcontent.split("&");
        NameValuePair pair[] = new NameValuePair[kvs.length];
        for (int i = 0; i < kvs.length; i++) {
            String kv[] = kvs[i].split("=");
            Object key = kv[0];
            String value = "";
            if (kv.length > 1) {
                value = kv[1] == null || kv[1].equals("null") ? "" : kv[1];
            }

            pair[count] = new NameValuePair((String) key, (String) value);
            count++;
        }

        return pair;
    }
    /**
     * @Author zhangli
     * @Description //TODO  自动进行cookie 处理，无需对再对cookie进行处理了
     * @Date 09:36 2019/4/25
     * @Param [httpMethod, httpClient]
     * @return void
     **/
    public void autoCookie(HttpMethod httpMethod,HttpClient httpClient){
        Cookie[] cookies=httpClient.getState().getCookies();
        String tmpcookies= "";
        for(Cookie c:cookies){
            tmpcookies += c.toString()+";";
        }

        //每次访问需授权的网址时需带上前面的 cookie 作为通行证
        httpMethod.setRequestHeader("cookie",tmpcookies);

    }

}
